﻿using System;
using System.Collections.Generic;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Newtonsoft.Json;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic.Statistics
{
    public class StatisticHistoryLogic : IStatisticHistoryLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IStatisticHistoryRepository _statisticHistoryRepository;

        public StatisticHistoryLogic(
            IStatisticHistoryRepository statisticHistoryRepository
        )
        {
            _statisticHistoryRepository = statisticHistoryRepository;
        }

        /// <summary>
        /// 保存统计数据
        /// </summary>
        /// <typeparam name="T">统计数据的类型，是哪个viewmodel</typeparam>
        /// <param name="projectId">项目id</param>
        /// <param name="statisticType">对象的类型</param>
        /// <param name="data">对象数据</param>
        /// <returns>成功，失败</returns>
        public bool Save<T>(string projectId, StatisticType statisticType, T data)
        {
            var json = JsonConvert.SerializeObject(data);
            return _statisticHistoryRepository.Add(projectId, statisticType, json) > 0;
        }

        /// <summary>
        /// 获取最新的一条统计数据
        /// </summary>
        /// <typeparam name="T">统计数据的类型，是哪个viewmodel</typeparam>
        /// <param name="projectId">项目id</param>
        /// <param name="statisticType">对象的类型</param>
        /// <returns>返回的对象</returns>
        public T GetNewData<T>(string projectId, StatisticType statisticType)
        {
            try
            {
                var data = _statisticHistoryRepository.GetNewStatisticData(projectId, statisticType);
                var result = JsonConvert.DeserializeObject<T>(data);
                return result;
            }
            catch (Exception e)
            {
                _logger.Error(e);
               return default(T);
            }
            
        }
    }
}